// var data_dict = eval('('+ '{{data_dict|safe}}' +')'); //注意django用json.dumps,前端需加|safe
// var default_engine = data_dict.default_engine;

var globalSid = 0;//全局id，用来添加tab时，绑定自定义属性
var formIndex;//打开的表单索引

var $,layer,form,element;
layui.use(['jquery', 'layer', 'form', 'element'], function () {
    $ = layui.jquery;
    layer = layui.layer;
    form = layui.form;
    element = layui.element;

    //自定义验证规则
    form.verify({
        type: function(value){
            if(value.length > 15){
                return '不能超过15个字符';
            }
        }
        ,name: function(value){
            if(value.length > 20){
                return '不能超过20个字符';
            }
        }
        ,site: function(value){
            if(value.length > 100){
                return '不能超过100个字符';
            }

            var _regular = '^file';
            if(value.match(_regular)){
                return '请输入有效网址';
            }
        }
    });

    $('#searchInput').bind('keypress',function(event){
        if(event.keyCode == "13"){
            goSearch();
        }
    });

    $("#custom").click(function(){
        $('#addTypeDiv').show();
        $('span.ele-hidden').show();
        $(this).hide();
        $("#saveGlobal").show();

        bindDrag();
        bindTypeDrag();
    });

    $("#saveGlobal").click(function(){
        var data = composeData();
        $.ajax({
            type: 'POST',
            url: "save",
            contentType: "application/json;charset=utf-8",
            data: data,
            dataType: "json",
            success:function (message) {
            },
            error:function (message) {
            }
        });

        $('#addTypeDiv').hide();
        $('span.ele-hidden').hide();
        $(this).hide();
        $("#custom").show();

        unBindDrag();
        unBindTypeDrag();
    });

    globalSid = $('.layui-tab-title').find('li').length;
    initLogo();
    bindTypeHover();
});

function initLogo(){
    var defaultEngine = $('#logoImg').attr('defaultEngine');
    if('google' === defaultEngine){
        $('#searchInput').attr('placeholder', '在 Google 上搜索，或者输入一个网址');
    } else {
        $('#searchInput').attr('placeholder', '百度一下，你就知道！');
    }
}

function switchLogo(){
    var defaultEngine = $('#logoImg').attr('defaultEngine');
    if('baidu' === defaultEngine){
        $('#logoImg').attr('defaultEngine', 'google');
        $('#logoImg').attr('src', '../static/img/google.png');
        $('#searchInput').attr('placeholder', '在 Google 上搜索，或者输入一个网址');
    } else {
        $('#logoImg').attr('defaultEngine', 'baidu');
        $('#logoImg').attr('src', '../static/img/baidu.png');
        $('#searchInput').attr('placeholder', '百度一下，你就知道！');
    }
}

//跳转搜索
function goSearch(){
    var key = $('#searchInput').val().trim();
    if('' !== key){
        var defaultEngine = $('#logoImg').attr('defaultEngine');
        if('baidu' === defaultEngine){
            window.open("https://www.baidu.com/s?wd="+ key, "_blank");
        } else {
            window.open("https://www.google.com/search?q="+ key, "_blank");
        }
    }
}

function layerCancel(){
    layer.close(formIndex);
}

/**
 * 添加分类
 */
function addType(){
    //初始化为空
    $('#editTypeForm').find('input[name="type"]').val('');
    formIndex = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        content: $('#editTypeForm')
    });

    form.on('submit(editTypeFormSubmit)', function(data){
        console.log(JSON.stringify(data.field));

        //赋值，在关闭页面时
        var typeVal = $('#editTypeForm').find('input[name="type"]').val();
        globalSid += 1;
        element.tabAdd('siteTab', {
            title: typeVal
            ,content: '' //支持传入html
            ,id: globalSid
        });
        //切换到指定的Tab项上
        element.tabChange('siteTab', globalSid);

        //追加图标
        var html_icon = '<span class="ele-hidden" sid="'+globalSid+'" style="display: inline;">'
                        + '<i class="layui-icon layui-icon-edit custom-edit" onclick="editType(this);"></i>'
                        + '<i class="layui-icon layui-icon-close custom-close" onclick="deleteType(this);"></i>'
                      + '</span>';
        $('.layui-tab-title').find('li[lay-id="'+globalSid+'"]').after(html_icon);
        
        //绑定sid
        $('.layui-tab-item').last().attr('sid', globalSid);

        bindTypeHover();
        layerCancel();
        
        return false;
    });
}

/**
 * 添加站点
 * 默认向当前选中的tab里添加
 */
function addSite(){
    //初始化为空
    $('#editSiteForm').find('input[name="name"]').val('');
    $('#editSiteForm').find('input[name="site"]').val('');
    formIndex = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        content: $('#editSiteForm')
    });

    form.on('submit(editSiteFormSubmit)', function(data){
        console.log(JSON.stringify(data.field));

        //赋值，在关闭页面时
        var nameVal = $('#editSiteForm').find('input[name="name"]').val();
        var siteVal = $('#editSiteForm').find('input[name="site"]').val();
        if (!siteVal.match("^http")) {
            siteVal = 'http://' + siteVal;
        }
        
        var html_site = '<span class="span-site">'
                            + '<a href="'+ siteVal +'" target="_blank" title="'+ nameVal +'" class="layui-btn layui-btn-primary a-site" lay-event="show">'
                            +    nameVal
                            + '</a>'
                            + '<span class="ele-hidden" style="display: inline;">'
                            + '    <i class="layui-icon layui-icon-edit custom-edit" onclick="editSite(this);"></i>'
                            + '    <i class="layui-icon layui-icon-close custom-close" onclick="deleteSite(this);"></i>'
                            + '</span>'
                      + '</span>';

        //找到layui-show，追加到末尾
        $('.layui-show').append(html_site);

        element.render();
        // element.render('tab', 'siteTab');

        layerCancel();
        
        return false;
    });
}

function editType(t){
    //赋值，在打开页面时
    var ele_li = $(t).closest('span').prev();
    $('#editTypeForm').find('input[name="type"]').val($(ele_li).text().trim());

    formIndex = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        content: $('#editTypeForm')
    });

    form.on('submit(editTypeFormSubmit)', function(data){
        console.log(JSON.stringify(data.field));

        //赋值，在关闭页面时
        var typeVal = $('#editTypeForm').find('input[name="type"]').val();
        $(ele_li).text(typeVal);

        layerCancel();
        
        return false;
    });
}
function deleteType(t){
    var lay_id = $(t).closest('span').prev().attr('lay-id');
    console.log('lay_id:'+lay_id);

    // 需删除自定义图标，否则删除tab时有问题
    $('.layui-tab-title').find('span.ele-hidden[sid="'+lay_id+'"]').remove();
    
    // tabDelete删除有问题，可能是加了span标签导致，手动删除
    // element.tabDelete('siteTab', lay_id);

    $('.layui-tab-title').find('li[lay-id="'+lay_id+'"]').remove();
    $('.layui-tab-item[sid="'+lay_id+'"]').remove();
}

function editSite(t){
    //赋值，在打开页面时
    var ele_a = $(t).closest('span.span-site').find('a');
    $('#editSiteForm').find('input[name="name"]').val($(ele_a).text().trim());
    $('#editSiteForm').find('input[name="site"]').val($(ele_a).attr('href'));

    formIndex = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        content: $('#editSiteForm')
    });

    form.on('submit(editSiteFormSubmit)', function(data){
        console.log(JSON.stringify(data.field));

        //赋值，在关闭页面时
        var nameVal = $('#editSiteForm').find('input[name="name"]').val();
        var siteVal = $('#editSiteForm').find('input[name="site"]').val();
        if (!siteVal.match("^http")) {
            siteVal = 'http://' + siteVal;
        }
        $(ele_a).text(nameVal);
        $(ele_a).attr('href', siteVal);

        layerCancel();
        
        return false;
    });
}

function deleteSite(t){
    $(t).closest('span.span-site').remove();
}

/**
 * 组装数据，为了简单，所有接口都用
 */
function composeData(){
    var defaultEngine = $('#logoImg').attr('defaultEngine');

    var data = '{'
            data += '"default_engine":"'+ defaultEngine +'",';
            data += '"category":[';

            var category_len = $('.layui-tab-title').find('li').length;
            $('.layui-tab-title').find('li').each(function(index,ele){
                data += '{';//category start

                var type = $(this).text().trim();
                data += '"type":' + '"'+ type +'",';
                data += '"sites":[';//sites start

                var site_len = $('.layui-tab-item').eq(index).find('.span-site').length;
                $('.layui-tab-item').eq(index).find('.span-site').each(function(index2,ele2){
                    var ele_a = $(this).find('a');
                    var name = $(ele_a).text().trim();
                    var site = $(ele_a).attr('href');

                    data += '{';
                        data += '"name":"'+ name +'",';
                        data += '"site":"'+ site +'"';
                    data += '}';

                    if((index2 + 1) < site_len){
                        data += ',';
                    }
                })
                data += ']';//sites end

                data += '}';//category end

                if((index + 1) < category_len){
                    data += ',';
                }
            });

            data += ']';
        data += '}';

    console.log("final data:"+data);
    return data;
}

/**
 * 绑定拖动
 */
function bindDrag(){
    $('.layui-tab-item').each(function(index,ele){
        new Sortable(ele, {
            handle: '.a-site',
            onStart: function(event, ui) {
                // $('#ul-tab').find('li').each(function(index,ele2){
                //     $(ele2).css('z-index',99999);
                // })
                // $(ele).css('z-index',-1);
                // console.log('zIndex:'+ $(ele).css('z-index'));
            }
        });
    })
}
/**
 * 取消绑定拖动
 */
function unBindDrag(){
    $('.layui-tab-item').each(function(index,ele){
        new Sortable(ele, {
            handle: '.a-site'
        }).destroy();
    })
}

/**
 * 绑定type拖动
 */
function bindTypeDrag(){
    new Sortable(document.getElementById('ul-tab'), {
        // handle: '.span-type'// Element dragging ended
        onEnd: function (/**Event*/evt) {
            var itemEl = evt.item;  // dragged HTMLElement

            //暴力排序
            $('#ul-tab').find('li').each(function(index,ele){
                var lay_id = $(this).attr('lay-id');
                $(this).after($('#ul-tab').find('span[sid="'+ lay_id +'"]'));
            })

            //拖动后元素的对应索引
            var after_lay_id = $(itemEl).attr('lay-id');
            var positionIndex = $('#ul-tab > li').index($(itemEl));
            var nextIndex = $('.layui-tab-content > .layui-tab-item[sid="'+ after_lay_id +'"]').index();

            //拖动时有两个方向：往左、往右，分别调用insertBefore、insertAfter
            if(positionIndex < nextIndex){
                $('.layui-tab-content').find('.layui-tab-item[sid="'+ after_lay_id +'"]').insertBefore($(".layui-tab-content > .layui-tab-item").eq(positionIndex));
            } else {
                $('.layui-tab-content').find('.layui-tab-item[sid="'+ after_lay_id +'"]').insertAfter($(".layui-tab-content > .layui-tab-item").eq(positionIndex));
            }

            element.render();
        },
    });
}
/**
 * 取消绑定type拖动
 */
function unBindTypeDrag(){
    new Sortable(document.getElementById('ul-tab'), {
        // handle: '.span-type'
    }).destroy();;
}

/**
 * 绑定type鼠标悬浮事件
 */
function bindTypeHover(){
    $('#ul-tab').find('li').each(function(index,ele){
        $(this).mouseover(function(){
            var lay_id = $(this).attr('lay-id');
            element.tabChange('siteTab', lay_id);
        })
    })
}
